package com.example.travel_front.Fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.fragment.app.Fragment
import com.mapbox.maps.MapView
import com.example.travel_front.R
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.Style
import com.mapbox.maps.extension.style.image.image
import com.mapbox.maps.extension.style.layers.generated.symbolLayer
import com.mapbox.maps.extension.style.layers.properties.generated.IconAnchor
import com.mapbox.maps.extension.style.sources.generated.geoJsonSource
import com.mapbox.maps.extension.style.style

class MapFragment : Fragment() {

    private var mapView: MapView? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.item_map, container, false)
        mapView = view.findViewById(R.id.mapView)

        mapView?.getMapboxMap()?.also {
            it.setCamera(
                CameraOptions.Builder()
                    .center(Point.fromLngLat(LONGITUDE, LATITUDE))
                    .zoom(12.0)
                    .build()
            )
        }?.loadStyle(
            styleExtension = style(Style.STANDARD) {
                // prepare blue marker from resources
                +image(
                    BLUE_ICON_ID,
                    ContextCompat.getDrawable(requireContext(), R.drawable.red_marker)!!.toBitmap()
                )
                +geoJsonSource(SOURCE_ID) {
                    geometry(Point.fromLngLat(LONGITUDE, LATITUDE))
                }
                +symbolLayer(LAYER_ID, SOURCE_ID) {
                    iconImage(BLUE_ICON_ID)
                    iconAnchor(IconAnchor.BOTTOM)
                    iconSize(0.5)
                }
            }
        )

        return view
    }



    @SuppressLint("Lifecycle")
    override fun onStart() {
        super.onStart()
        mapView?.onStart()
    }

    @SuppressLint("Lifecycle")
    override fun onStop() {
        super.onStop()
        mapView?.onStop()
    }

    @SuppressLint("Lifecycle")
    override fun onDestroyView() {
        super.onDestroyView()
        mapView?.onDestroy()
    }

    @SuppressLint("Lifecycle")
    override fun onLowMemory() {
        super.onLowMemory()
        mapView?.onLowMemory()
    }

    companion object {
        private const val BLUE_ICON_ID = "blue"
        private const val SOURCE_ID = "source_id"
        private const val LAYER_ID = "layer_id"
        private const val LONGITUDE = -74.0060
        private const val LATITUDE = 40.7128
    }
}
